package com.rbcs.budget.webapp;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.rbcs.base.model.Item;
import com.rbcs.base.model.Project;
import com.rbcs.budget.model.ProjectBudget;
import com.rbcs.budget.model.ProjectItemBudget;
import com.rbcs.budget.service.ProjectBudgetManager;
import com.rbcs.budget.service.ProjectItemBudgetManager;
import com.rbcs.flow.FlowConstants;
import com.rbcs.flow.service.FlowManager;
import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.ApplicationException;
import com.systop.core.util.DateUtil;
import com.systop.core.util.PageUtil;
import com.systop.core.webapp.struts2.action.DefaultCrudAction;

/**
 * 项目预算
 * 
 * @author Nice
 */
@SuppressWarnings("serial")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ProjectBudgetAction extends
		DefaultCrudAction<ProjectBudget, ProjectBudgetManager> {

	@Autowired
	private ProjectItemBudgetManager projectItemBudgetManager;

	@Autowired
	private FlowManager flowManager;

	// 项目预算组成部门ProjectItemBudget的id集合
	private Integer[] pibIds;

	/**
	 * 新建项目预算,选择项目后先生成项目预算的结构
	 */
	public String editNew() {
		if (getModel() != null && getModel().getProject() != null) {
			Project prj = getManager().getDao().get(Project.class,
					getModel().getProject().getId());
			if (prj != null) {
				getModel().setCreater(UserUtil.getPrincipal(getRequest()));
				getModel().setCreateTime(new Date());
				getModel().setProject(prj);
				getModel().setAmount(0.0);
				if (getManager().getDao().exists(getModel(), "project.id")) {
					addActionError("【" + prj.getName() + "】已经存在项目预算，不能重复定制预算");
					getModel().setProject(null);// 为页面准备
					return INPUT;
				}
				List<Item> items = prj.getProjectType().getItems();
				if (items != null && !items.isEmpty()) {// 循环预算科目
					String sn = DateUtil.getDateTime("yyyyMMddHHmm", new Date());
					getModel().setSingleNo("XMYS-" + sn);
					try {
						getManager().save(getModel());// 第一次保存项目预算
					} catch (ApplicationException e) {
						addActionError(e.getMessage());
						return INPUT;
					}
					for (Item item : items) {
						ProjectItemBudget pib = new ProjectItemBudget();
						pib.setItem(item);
						pib.setProjectBudget(getModel());
						projectItemBudgetManager.save(pib);
					}
					addActionMessage("项目预算初始化成功,请填写每项科目预算额");
				} else {
					addActionError("该项目所属类别未配置预算科目");
					return INPUT;
				}
			}
		}
		return "editNewSuccess";
	}

	/**
	 * 修改预算，保存预算
	 */
	public String save() {
		try {
			if (pibIds != null) {
				Double amount = 0.0;
				for (Integer id : pibIds) {
					ProjectItemBudget pib = projectItemBudgetManager.get(id);
					setupData(pib);
					projectItemBudgetManager.save(pib);
					amount = amount + pib.getFinalAmount();// 计算项目预算额
				}
				getModel().setAmount(amount);
				getManager().save(getModel());
				addActionMessage("项目预算保存成功");
			}
		} catch (ApplicationException e) {
			addActionError(e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}

	// 根据ProjectItemBudget'id组合参数名称，装填数据
	private void setupData(ProjectItemBudget pib) {
		if (pib == null || pib.getId() == null) {
			return;
		}
		Integer id = pib.getId();
		pib.setAmount(getDoubleValue("pibAmount_", id));// 预算额
		pib.setAdd1th(getDoubleValue("pibAdd1th_", id));
		pib.setAdd2th(getDoubleValue("pibAdd2th_", id));
		pib.setAdd3th(getDoubleValue("pibAdd3th_", id));
		pib.setAdd4th(getDoubleValue("pibAdd4th_", id));
		pib.setFinalAmount(pib.getAmount() + pib.getAdd1th() + pib.getAdd2th()
				+ pib.getAdd3th() + pib.getAdd4th());
	}

	// 获得参数值，并转换成Double类型
	private Double getDoubleValue(String parmarPre, Integer id) {
		String doubleValue = getRequest().getParameter(parmarPre + id);
		if (StringUtils.isNotBlank(doubleValue)) {
			return Double.valueOf(doubleValue);
		}
		return 0.0;
	}

	/**
	 * 项目拥有者,或者预算制定者
	 */
	public String index() {
		StringBuffer hql = new StringBuffer();
		hql.append("from ProjectBudget b where b.project != null and (b.project.managerIds like ? or b.creater.id = ?) ");
		hql.append("order by createTime desc");
		page = PageUtil.getPage(getPageNo(), getPageSize());
		User user = getLoginUser();
		page = getManager().pageQuery(page, hql.toString(),
				new Object[] { "%" + user.getId() + "%", user.getId() });
		restorePageData(page);
		return INDEX;
	}

	/**
	 * 创建审核流程节点
	 * 
	 * @return
	 */
	public String createAudFlow() {
		if (getModel() != null && getModel().getId() != null) {
			if (StringUtils.isNotBlank(getModel().getProject().getManagerIds())) {
				flowManager.createProjectBudgetFlow(getModel());
				getModel().setAudStatus(FlowConstants.AUDIT_PENDING);
				getManager().save(getModel());
			}
		}
		return "createFlowSuccess";
	}
	
	// 当前登录用户
	private User getLoginUser() {
		User user = UserUtil.getLoginUser(getRequest());
		user = getManager().getDao().get(User.class, user.getId());
		return user;
	}

	public Integer[] getPibIds() {
		return pibIds;
	}

	public void setPibIds(Integer[] pibIds) {
		this.pibIds = pibIds;
	}
}
